
package com.hlkj.pay.app.merchant.ext.impl.wxpay;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.math.BigDecimal;
import java.security.PublicKey;
import java.time.format.DateTimeFormatter;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.extension.annotation.Extension;
import com.hlkj.pay.app.merchant.ext.ChannelMerchantProfitOrderExtPt;
import com.hlkj.pay.app.merchant.ext.MerchantExtConstant;
import com.hlkj.pay.app.merchant.ext.dto.profit.ChannelProfitOrderContext;
import com.hlkj.pay.app.merchant.ext.dto.profit.ChannelProfitOrderQueryContext;
import com.hlkj.pay.app.merchant.ext.impl.wxpay.constant.WxPayExtConstant;
import com.hlkj.pay.app.merchant.ext.impl.wxpay.dto.WxAppChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.wxpay.dto.WxPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.wxpay.dto.WxProfitReceiverModel;
import com.hlkj.pay.app.merchant.ext.impl.wxpay.dto.WxProfitResp;
import com.hlkj.pay.app.merchant.ext.impl.wxpay.handler.WxPayCommonParamsHandle;
import com.hlkj.pay.common.MerchantResultCode;
import com.hlkj.pay.dto.order.PayOrderFundDto;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayOrderEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAppChannelDO;
import com.hlkj.pay.infrastructure.model.order.OrderFundDO;
import com.hlkj.pay.infrastructure.model.order.OrderFundDetailDO;
import com.hlkj.pay.infrastructure.model.order.PayOrderDO;
import com.hlkj.pay.util.DateUtils;
import com.hlkj.pay.util.HttpRequestUtil;
import com.hlkj.pay.util.MerchantUtils;
import com.ijpay.core.IJPayHttpResponse;
import com.ijpay.core.enums.AuthTypeEnum;
import com.ijpay.core.enums.RequestMethodEnum;
import com.ijpay.core.kit.PayKit;
import com.ijpay.core.kit.RsaKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.enums.WxApiType;
import com.ijpay.wxpay.enums.WxDomainEnum;
import com.ijpay.wxpay.model.ReceiverModel;
import com.ijpay.wxpay.model.v3.ProfitSharingModel;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @date 2025/01/06 17:47
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Extension(bizId = MerchantExtConstant.CHANNEL_WX_PAY)
public class WxPayMerchantProfitOrderExtPt implements ChannelMerchantProfitOrderExtPt {

    private final WxPayCommonParamsHandle wxPayCommonParamsHandle;

    @Value("${hlkj.domain}")
    private String domain;

    @Override
    public void submitOrderProfit(ChannelProfitOrderContext channelProfitOrderContext) {
        // 判断商户类型
        MerchantAppChannelDO merchantAppChannelDO = channelProfitOrderContext.getMerchantAppChannelDO();
        if(merchantAppChannelDO.getType() != null && MerchantEnum.APP_CHANNEL_TYPE.MERCHANT_COMMON.getCode()  == merchantAppChannelDO.getType()){
            channelProfitOrderContext.setRemark("微信普通商户不支持分账");
            channelProfitOrderContext.setProcessStatus(false);
            return;
        }
        CommonResult<WxPayConfig> wxPayConfigCommonResult = wxPayCommonParamsHandle.wxPayConfig(channelProfitOrderContext.getProviderChannelConfig(),
                channelProfitOrderContext.isTest());
        if (!wxPayConfigCommonResult.isSuccess()) {
            channelProfitOrderContext.setRemark(wxPayConfigCommonResult.getMsg());
            channelProfitOrderContext.setProcessStatus(false);
            return;
        }
        // 微信配置信息
        WxPayConfig wxPayConfig = wxPayConfigCommonResult.getData();
        // 支付订单信息
        PayOrderDO payOrderDO = channelProfitOrderContext.getPayOrderDO();
        // 服务商
        WxAppChannelParams WxAppChannelParams = JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), WxAppChannelParams.class);
        // 获取公众号ID
        String pubAppid = wxPayCommonParamsHandle.getAppid(channelProfitOrderContext.getProviderChannelConfig(), CommonEnum.COMMON_APP_TYPE.WECHAT_PUB);
        try {
            // 支付公钥 敏感信息加密
            PublicKey publicKey = RsaKit.loadPublicKey(PayKit.getPublicKeyByContent(PayKit.getCertFileContent(wxPayConfig.getPayPublicPath())));
            // 分账接收方列表
            List<PayOrderFundDto> payOrderFundList = channelProfitOrderContext.getPayOrderFundDtoList();
            // 批次号
            String batchNo = payOrderFundList.get(0).getBatchNo();
            // 组装分账接收方参数
            List<ReceiverModel> receivers = new ArrayList<>();
            for(PayOrderFundDto fundDto:payOrderFundList){
                ReceiverModel receiverModel = new ReceiverModel();
                receiverModel.setType("PERSONAL_OPENID");
                if(StrUtil.isNotEmpty(fundDto.getName())){
                    receiverModel.setName(wxPayCommonParamsHandle.rsaEncryptOAEP(fundDto.getName(),publicKey));
                }
                receiverModel.setAccount(fundDto.getAccountNo());
                receiverModel.setDescription(fundDto.getDescription());
                receiverModel.setAmount(MerchantUtils.YuanToFen(new BigDecimal(fundDto.getAmount())));
                receivers.add(receiverModel);
            }

            // String notifyUrl = domain + MerchantExtConstant.MERCHANT_ORDER_DIVICE_CALLBACK_URL + payOrderDO.getChannelCode() +
            //         StringPool.SLASH + payOrderDO.getProviderCode()+ StringPool.SLASH + batchNo;

            ProfitSharingModel profitSharingModel = new ProfitSharingModel()
                    .setSub_mchid(WxAppChannelParams.getSubMchId())
                    .setAppid(pubAppid)
                    .setTransaction_id(payOrderDO.getChannelOrderNo())
                    .setOut_order_no(batchNo)
                    .setReceivers(receivers);

            log.info("微信提交分账 请求参数:{}", JSONUtil.toJsonStr(profitSharingModel));
            // 响应参数
            IJPayHttpResponse response = WxPayApi.v3(
                    RequestMethodEnum.POST,
                    WxDomainEnum.CHINA.toString(),
                    WxApiType.V3_PROFIT_SHARING_ORDERS.toString(),
                    wxPayConfig.getMchId(),
                    wxPayConfig.getSerialNo(),
                    wxPayConfig.getPayPublicId(),
                    wxPayConfig.getPrivateKeyPath(),
                    JSONUtil.toJsonStr(profitSharingModel),
                    AuthTypeEnum.RSA.getCode()
            );
            log.info("微信提交分账 返回参数:{}", JSONUtil.toJsonStr(response));
            JSONObject resp = JSONUtil.parseObj(response.getBody());
            if (response.getStatus() == WxPayExtConstant.OK ) {
                WxProfitResp result = JSONUtil.toBean(response.getBody(),WxProfitResp.class);
                for(PayOrderFundDto payOrderFundDO:payOrderFundList){
                    Optional<WxProfitReceiverModel> wxProfitReceiverModelOptional = result.getReceivers().stream().filter(receiver -> receiver.getAccount().equals(payOrderFundDO.getAccountNo())).findFirst();
                    if(wxProfitReceiverModelOptional.isPresent()){
                        WxProfitReceiverModel wxProfitReceiverModel = wxProfitReceiverModelOptional.get();
                        PayOrderEnums.PAY_ORDER_FUND_STATUS subPayOrderFundStatus = null;
                        String subFailMsg = null;
                        switch (wxProfitReceiverModel.getResult()){
                            case "PENDING":
                                subPayOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.FUNDING;
                                break;
                            case "SUCCESS":
                                subPayOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.SUCCESS;
                                break;
                            case "FAIL":
                                subPayOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.FAIL;
                                subFailMsg = wxProfitReceiverModel.getFail_reason();
                                break;
                        }
                        payOrderFundDO.setFundStatus(subPayOrderFundStatus);
                        payOrderFundDO.setType(wxProfitReceiverModel.getType());
                        payOrderFundDO.setDetailId(wxProfitReceiverModel.getDetail_id());
                        payOrderFundDO.setSuccessTime(DateUtils.shanghaiDate(wxProfitReceiverModel.getFinish_time(), DateTimeFormatter.ISO_OFFSET_DATE_TIME));
                        if(StrUtil.isNotEmpty(subFailMsg)){
                            payOrderFundDO.setFailReason(subFailMsg);
                        }
                    }
                }
            }else{
                channelProfitOrderContext.setProcessStatus(Boolean.FALSE);
                channelProfitOrderContext.setRemark(resp.getStr("message"));
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            channelProfitOrderContext.setRemark("微信提交订单分账请求失败,失败信息:" + e.getMessage());
            channelProfitOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    @Override
    public void queryOrderProfit(ChannelProfitOrderQueryContext channelProfitOrderQueryContext) {
        // 判断商户类型
        MerchantAppChannelDO merchantAppChannelDO = channelProfitOrderQueryContext.getMerchantAppChannelDO();
        if(merchantAppChannelDO.getType() != null && MerchantEnum.APP_CHANNEL_TYPE.MERCHANT_COMMON.getCode()  == merchantAppChannelDO.getType()){
            channelProfitOrderQueryContext.setRemark("微信普通商户不支持分账");
            channelProfitOrderQueryContext.setProcessStatus(false);
            return;
        }
        CommonResult<WxPayConfig> wxPayConfigCommonResult = wxPayCommonParamsHandle.wxPayConfig(channelProfitOrderQueryContext.getProviderChannelConfig(),
                channelProfitOrderQueryContext.isTest());
        if (!wxPayConfigCommonResult.isSuccess()) {
            channelProfitOrderQueryContext.setRemark(wxPayConfigCommonResult.getMsg());
            channelProfitOrderQueryContext.setProcessStatus(false);
            return;
        }
        // 微信配置信息
        WxPayConfig wxPayConfig = wxPayConfigCommonResult.getData();
        // 支付订单信息
        PayOrderDO payOrderDO = channelProfitOrderQueryContext.getPayOrderDO();
        // 服务商
        WxAppChannelParams WxAppChannelParams = JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), WxAppChannelParams.class);
        try {
            List<OrderFundDetailDO> payOrderFundList = channelProfitOrderQueryContext.getPayOrderFunds();
            // 批次号
            String batchNo = payOrderFundList.get(0).getBatchNo();

            Map<String,Object> reqBody = new HashMap<>();
            reqBody.put("sub_mchid",WxAppChannelParams.getSubMchId());
            reqBody.put("transaction_id",payOrderDO.getChannelOrderNo());

            log.info("微信提交分账查询 请求参数:{}", JSONUtil.toJsonStr(reqBody));
            // 响应参数
            IJPayHttpResponse response = WxPayApi.v3(
                    RequestMethodEnum.GET,
                    WxDomainEnum.CHINA.toString(),
                    "/v3/profitsharing/orders/"+batchNo+"?"+ HttpUtil.toParams(reqBody),
                    wxPayConfig.getMchId(),
                    wxPayConfig.getSerialNo(),
                    wxPayConfig.getPayPublicId(),
                    wxPayConfig.getPrivateKeyPath(),
                    "",
                    AuthTypeEnum.RSA.getCode()
            );
            log.info("微信提交分账查询 返回参数:{}", JSONUtil.toJsonStr(response));
            JSONObject resp = JSONUtil.parseObj(response.getBody());
            if (response.getStatus() == WxPayExtConstant.OK ) {
                WxProfitResp result = JSONUtil.toBean(response.getBody(),WxProfitResp.class);
                for(OrderFundDetailDO fundDetailDO:payOrderFundList){
                    Optional<WxProfitReceiverModel> wxProfitReceiverModelOptional = result.getReceivers().stream().filter(receiver -> receiver.getAccount().equals(fundDetailDO.getAccountNo())).findFirst();
                    if(wxProfitReceiverModelOptional.isPresent()){
                        WxProfitReceiverModel wxProfitReceiverModel = wxProfitReceiverModelOptional.get();
                        PayOrderEnums.PAY_ORDER_FUND_STATUS subPayOrderFundStatus = null;
                        String subFailMsg = null;
                        switch (wxProfitReceiverModel.getResult()){
                            case "PENDING":
                                subPayOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.FUNDING;
                                break;
                            case "SUCCESS":
                                subPayOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.SUCCESS;
                                break;
                            case "FAIL":
                                subPayOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.FAIL;
                                subFailMsg = wxProfitReceiverModel.getFail_reason();
                                break;
                        }
                        fundDetailDO.setFundStatus(subPayOrderFundStatus.getCode());
                        fundDetailDO.setType(wxProfitReceiverModel.getType());
                        fundDetailDO.setDetailId(wxProfitReceiverModel.getDetail_id());
                        fundDetailDO.setSuccessTime(DateUtils.shanghaiDate(wxProfitReceiverModel.getFinish_time(),  DateTimeFormatter.ISO_OFFSET_DATE_TIME));
                        if(StrUtil.isNotEmpty(subFailMsg)){
                            fundDetailDO.setFailReason(subFailMsg);
                        }
                    }
                }
            }else{
                channelProfitOrderQueryContext.setProcessStatus(Boolean.FALSE);
                channelProfitOrderQueryContext.setRemark(resp.getStr("message"));
            }

        }
        catch (Exception e) {
            channelProfitOrderQueryContext.setRemark("微信提交分账查询请求失败,失败信息:" + e.getMessage());
            channelProfitOrderQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    @Override
    public void submitRefundOrderProfit(ChannelProfitOrderContext channelProfitOrderContext) {

        channelProfitOrderContext.setRemark("微信 不支持针对“分账到零钱”的分账单发起分账回退");
        channelProfitOrderContext.setProcessStatus(Boolean.FALSE);

        // 判断商户类型
        // MerchantAppChannelDO merchantAppChannelDO = channelProfitOrderContext.getMerchantAppChannelDO();
        // if(merchantAppChannelDO.getType() != null && MerchantEnum.APP_CHANNEL_TYPE.MERCHANT_COMMON.getCode()  == merchantAppChannelDO.getType()){
        //     channelProfitOrderContext.setRemark("微信普通商户不支持分账");
        //     channelProfitOrderContext.setProcessStatus(false);
        //     return;
        // }
        // CommonResult<WxPayConfig> wxPayConfigCommonResult = wxPayCommonParamsHandle.wxPayConfig(channelProfitOrderContext.getProviderChannelConfig(),
        //         channelProfitOrderContext.isTest());
        // if (!wxPayConfigCommonResult.isSuccess()) {
        //     channelProfitOrderContext.setRemark(wxPayConfigCommonResult.getMsg());
        //     channelProfitOrderContext.setProcessStatus(false);
        //     return;
        // }
        // // 微信配置信息
        // WxPayConfig wxPayConfig = wxPayConfigCommonResult.getData();
        // // 支付订单信息
        // PayOrderDO payOrderDO = channelProfitOrderContext.getPayOrderDO();
        // // 服务商
        // WxAppChannelParams WxAppChannelParams = JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), WxAppChannelParams.class);


        // try {
        //     List<RefundOrderFundDto> payOrderFundList = channelProfitOrderContext.getRefundOrderFundDtoList();
        //     List<String> errMsg = new ArrayList<>();
        //     // 多个分账退款 轮询
        //     for(RefundOrderFundDto refundOrderFundDto:payOrderFundList){
        //         Map<String,Object> reqBody = new HashMap<>();
        //         reqBody.put("sub_mchid",WxAppChannelParams.getSubMchId());
        //         reqBody.put("out_order_no",refundOrderFundDto.getBatchNo());
        //         reqBody.put("out_return_no",payOrderDO.getPayOrderNo());
        //         reqBody.put("return_mchid",refundOrderFundDto.getAccountNo());
        //         reqBody.put("amount",MerchantUtils.YuanToFen(new BigDecimal(refundOrderFundDto.getAmount())));
        //         reqBody.put("description",refundOrderFundDto.getDescription());
        //
        //         log.info("微信提交分账退款 请求参数:{}", JSONUtil.toJsonStr(reqBody));
        //         // 响应参数
        //         IJPayHttpResponse response = WxPayApi.v3(
        //                 RequestMethodEnum.POST,
        //                 WxDomainEnum.CHINA.toString(),
        //                 WxApiType.V3_PROFIT_SHARING_RETURN_ORDERS.toString(),
        //                 wxPayConfig.getMchId(),
        //                 wxPayConfig.getSerialNo(),
        //                 wxPayConfig.getPayPublicId(),
        //                 wxPayConfig.getPrivateKeyPath(),
        //                 JSONUtil.toJsonStr(reqBody),
        //                 AuthTypeEnum.RSA.getCode()
        //         );
        //         log.info("微信提交分账退款 返回参数:{}", JSONUtil.toJsonStr(response));
        //         JSONObject resp = JSONUtil.parseObj(response.getBody());
        //         if (response.getStatus() == WxPayExtConstant.OK) {
        //             WxProfitRefundResp wxProfitRefundResp = JSONUtil.toBean(response.getBody(),WxProfitRefundResp.class);
        //             PayOrderEnums.PAY_ORDER_FUND_STATUS payOrderFundStatus = null;
        //             String failMsg = null;
        //             switch (wxProfitRefundResp.getResult()){
        //                 case "PENDING":
        //                     payOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.FUNDING;
        //                     break;
        //                 case "SUCCESS":
        //                     payOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.REFUND;
        //                     break;
        //                 case "FAIL":
        //                     payOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.FAIL;
        //                     failMsg = wxProfitRefundResp.getFail_reason();
        //                     break;
        //             }
        //             refundOrderFundDto.setFundStatus(payOrderFundStatus);
        //             if(StrUtil.isNotEmpty(failMsg)){
        //                 refundOrderFundDto.setFailReason(failMsg);
        //             }
        //         }else {
        //             errMsg.add(refundOrderFundDto.getAccountNo()+":"+resp.getStr("message")) ;
        //         }
        //     }
        //
        //     if(CollUtil.isNotEmpty(errMsg)){
        //         if(errMsg.size() < payOrderFundList.size()){
        //             channelProfitOrderContext.setRemark("微信提交分账退款 部分请求失败,失败信息:"+JSONUtil.toJsonStr(errMsg));
        //         }else{
        //             channelProfitOrderContext.setRemark("微信提交分账退款 请求失败,失败信息:"+JSONUtil.toJsonStr(errMsg));
        //         }
        //         channelProfitOrderContext.setProcessStatus(Boolean.FALSE);
        //     }
        // }
        // catch (Exception e) {
        //     log.error("微信提交分账退款请求失败 message:{}", e);
        //     channelProfitOrderContext.setRemark("微信提交分账退款请求失败,失败信息:" + e.getMessage());
        //     channelProfitOrderContext.setProcessStatus(Boolean.FALSE);
        // }
    }

    @Override
    public void queryRefundOrderProfit(ChannelProfitOrderQueryContext channelProfitOrderQueryContext) {

        channelProfitOrderQueryContext.setRemark("微信 不支持针对“分账到零钱”的分账单发起分账回退");
        channelProfitOrderQueryContext.setProcessStatus(Boolean.FALSE);

        // 判断商户类型
        // MerchantAppChannelDO merchantAppChannelDO = channelProfitOrderQueryContext.getMerchantAppChannelDO();
        // if(merchantAppChannelDO.getType() != null && MerchantEnum.APP_CHANNEL_TYPE.MERCHANT_COMMON.getCode()  == merchantAppChannelDO.getType()){
        //     channelProfitOrderQueryContext.setRemark("微信普通商户不支持分账");
        //     channelProfitOrderQueryContext.setProcessStatus(false);
        //     return;
        // }
        // CommonResult<WxPayConfig> wxPayConfigCommonResult = wxPayCommonParamsHandle.wxPayConfig(channelProfitOrderQueryContext.getProviderChannelConfig(),
        //         channelProfitOrderQueryContext.isTest());
        // if (!wxPayConfigCommonResult.isSuccess()) {
        //     channelProfitOrderQueryContext.setRemark(wxPayConfigCommonResult.getMsg());
        //     channelProfitOrderQueryContext.setProcessStatus(false);
        //     return;
        // }
        // // 微信配置信息
        // WxPayConfig wxPayConfig = wxPayConfigCommonResult.getData();
        // // 支付订单信息
        // PayOrderDO payOrderDO = channelProfitOrderQueryContext.getPayOrderDO();
        // // 服务商
        // WxAppChannelParams WxAppChannelParams = JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), WxAppChannelParams.class);
        // try {
        //     List<OrderFundDetailDO> payOrderFundList = channelProfitOrderQueryContext.getRefundOrderFunds();
        //
        //     for(OrderFundDetailDO fundDetailDO:payOrderFundList){
        //         Map<String,Object> reqBody = new HashMap<>();
        //         reqBody.put("sub_mchid",WxAppChannelParams.getSubMchId());
        //         reqBody.put("out_order_no",payOrderDO.getPayOrderNo());
        //
        //         log.info("微信提交分账退款查询 请求参数:{}", JSONUtil.toJsonStr(reqBody));
        //         // 响应参数
        //         IJPayHttpResponse response = WxPayApi.v3(
        //                 RequestMethodEnum.POST,
        //                 WxDomainEnum.CHINA.toString(),
        //                 String.format(WxApiType.V3_PROFIT_SHARING_RETURN_ORDERS_QUERY.toString(),fundDetailDO.getBatchNo()),
        //                 wxPayConfig.getMchId(),
        //                 wxPayConfig.getSerialNo(),
        //                 wxPayConfig.getPayPublicId(),
        //                 wxPayConfig.getPrivateKeyPath(),
        //                 JSONUtil.toJsonStr(reqBody),
        //                 AuthTypeEnum.RSA.getCode()
        //         );
        //         log.info("微信提交分账退款查询 返回参数:{}", JSONUtil.toJsonStr(response));
        //         if (response.getStatus() == WxPayExtConstant.OK ) {
        //             WxProfitRefundResp wxProfitRefundResp = JSONUtil.toBean(response.getBody(),WxProfitRefundResp.class);
        //             PayOrderEnums.PAY_ORDER_FUND_STATUS payOrderFundStatus = null;
        //             String failMsg = null;
        //             switch (wxProfitRefundResp.getResult()){
        //                 case "PROCESSING":
        //                     payOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.FUNDING;
        //                     break;
        //                 case "SUCCESS":
        //                     payOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.REFUND;
        //                     break;
        //                 case "FAIL":
        //                     payOrderFundStatus = PayOrderEnums.PAY_ORDER_FUND_STATUS.FAIL;
        //                     failMsg = wxProfitRefundResp.getFail_reason();
        //                     break;
        //             }
        //             fundDetailDO.setFundStatus(payOrderFundStatus.getCode());
        //             if(StrUtil.isNotEmpty(failMsg)){
        //                 fundDetailDO.setFailReason(failMsg);
        //             }
        //         }
        //     }
        // }
        // catch (Exception e) {
        //     log.error("微信提交分账退款查询失败请求失败 message:{}", e);
        //     channelProfitOrderQueryContext.setRemark("微信提交分账退款查询失败,失败信息:" + e.getMessage());
        //     channelProfitOrderQueryContext.setProcessStatus(Boolean.FALSE);
        // }
    }

    @Override
    public void finishAcctOrder(ChannelProfitOrderContext channelProfitOrderContext) {
        // 判断商户类型
        MerchantAppChannelDO merchantAppChannelDO = channelProfitOrderContext.getMerchantAppChannelDO();
        if(merchantAppChannelDO.getType() != null && MerchantEnum.APP_CHANNEL_TYPE.MERCHANT_COMMON.getCode()  == merchantAppChannelDO.getType()){
            channelProfitOrderContext.setRemark("微信普通商户不支持分账");
            channelProfitOrderContext.setProcessStatus(false);
            return;
        }
        CommonResult<WxPayConfig> wxPayConfigCommonResult = wxPayCommonParamsHandle.wxPayConfig(channelProfitOrderContext.getProviderChannelConfig(),
                channelProfitOrderContext.isTest());
        if (!wxPayConfigCommonResult.isSuccess()) {
            channelProfitOrderContext.setRemark(wxPayConfigCommonResult.getMsg());
            channelProfitOrderContext.setProcessStatus(false);
            return;
        }
        // 微信配置信息
        WxPayConfig wxPayConfig = wxPayConfigCommonResult.getData();
        // 支付订单信息
        PayOrderDO payOrderDO = channelProfitOrderContext.getPayOrderDO();
        // 服务商
        WxAppChannelParams WxAppChannelParams = JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), WxAppChannelParams.class);
        try {
            OrderFundDO orderFundDO = channelProfitOrderContext.getOrderFundDO();
            List<OrderFundDetailDO> payOrderFundList = channelProfitOrderContext.getOrderFundDetailDOList();

            Map<String,Object> reqBody = new HashMap<>();
            reqBody.put("sub_mchid",WxAppChannelParams.getSubMchId());
            reqBody.put("transaction_id",payOrderDO.getChannelOrderNo());
            reqBody.put("out_order_no", IdUtil.simpleUUID());
            reqBody.put("description","解冻全部剩余资金");

            log.info("微信完结分账 请求参数:{}", JSONUtil.toJsonStr(reqBody));
            // 响应参数
            IJPayHttpResponse response = WxPayApi.v3(
                    RequestMethodEnum.POST,
                    WxDomainEnum.CHINA.toString(),
                    WxApiType.PROFIT_SHARING_UNFREEZE.toString(),
                    wxPayConfig.getMchId(),
                    wxPayConfig.getSerialNo(),
                    wxPayConfig.getPayPublicId(),
                    wxPayConfig.getPrivateKeyPath(),
                    JSONUtil.toJsonStr(reqBody),
                    AuthTypeEnum.RSA.getCode()
            );
            log.info("微信完结分账 返回参数:{}", JSONUtil.toJsonStr(response));
            JSONObject resp = JSONUtil.parseObj(response.getBody());
            if (response.getStatus() == WxPayExtConstant.OK ) {
                WxProfitResp result = JSONUtil.toBean(response.getBody(),WxProfitResp.class);
                switch (result.getState()){
                    case "PROCESSING":
                    case "FINISHED":
                        orderFundDO.setFundStatus(PayOrderEnums.PAY_ORDER_FUND_STATUS.CLOSE.getCode());
                        break;
                    case "FAIL":
                        channelProfitOrderContext.setProcessStatus(false);
                        channelProfitOrderContext.setRemark("微信完结分账请求失败: " + JSONUtil.toJsonStr(result.getReceivers()));
                        break;
                }
            }else{
                channelProfitOrderContext.setProcessStatus(Boolean.FALSE);
                channelProfitOrderContext.setRemark(resp.getStr("message"));
            }
        }
        catch (Exception e) {
            log.error("微信完结分账请求失败请求失败 message:{}", e);
            channelProfitOrderContext.setRemark("微信完结分账请求失败请求失败,失败信息:" + e.getMessage());
            channelProfitOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    @Override
    public CommonResult<String> acctStatusParse(HttpServletRequest request, ChannelProfitOrderContext channelProfitOrderContext) {

        CommonResult<String> acctOrderDOCommonResult = CommonResult.success();
        try {
            String paramsConfig = channelProfitOrderContext.getProviderChannelConfig().getParamsConfig();
            // 微信配置信息
            WxPayConfig wxPayConfig = JsonUtils.parseObject(paramsConfig, WxPayConfig.class);

            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String serialNo = request.getHeader("Wechatpay-Serial");
            String signature = request.getHeader("Wechatpay-Signature");
            log.info("timestamp:{} nonce:{} serialNo:{} signature:{}", timestamp, nonce, serialNo, signature);
            String result = HttpRequestUtil.requestBodyParams(request);
            log.info("微信分账通知密文 {}", result);
            String plainText = null;
            // 微信公钥验证签名并解密
            if(serialNo.equals(wxPayConfig.getPayPublicId())){
                plainText = WxPayKit.verifyPublicKeyNotify(result, signature, nonce, timestamp,
                        wxPayConfig.getApiV3Key(), wxPayConfig.getPayPublicPath());
            }else if(serialNo.equals(wxPayCommonParamsHandle.getPlatSerialNumber(wxPayConfig))){
                plainText = WxPayKit.verifyNotify(serialNo,result, signature, nonce, timestamp,wxPayConfig.getApiV3Key(), wxPayConfig.getPlatformCertPath());
            }
            log.info("微信分账通知明文 {}", plainText);
        }
        catch (Exception e) {
            acctOrderDOCommonResult.setCode(MerchantResultCode.MERCHANT_CHANNEL_CALLBACK_SIGN_ERROR.getCode());
        }
        return acctOrderDOCommonResult;
    }

    @Override
    public void settleConfirm(ChannelProfitOrderContext channelProfitOrderContext) {

    }
}
